package com.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.entity.Cart;
import com.entity.Order;
import com.entity.Product;
import com.entity.ProductCategory;
import com.entity.User;
import com.entity.UserAddress;
import com.service.product.impl.OrderServiceImpl;
import com.service.product.impl.ProductServiceImpl;
import com.service.user.impl.UserServiceImpl;
import com.servlet.BaseServlet;
import com.utils.CartUtil;
import com.utils.Constants;
import com.utils.EmptyUtils;
import com.utils.ReturnResult;

/**
 * 购物车
 * @author 
 *
 */
@WebServlet("/CartServlet")
public class CartServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	/**
	 * 添加购物车
	 * @param request
	 * @param response
	 * @throws Exception 
	 */
	public ReturnResult addCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ReturnResult result = new ReturnResult();
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("easybuyUserLogin");
		if(user == null) {
			result.returnNo("您未登录，请先登录！");
		}else {
			int productid = Integer.parseInt(request.getParameter("entityId"));	//商品id
			int stock = Integer.parseInt(request.getParameter("quantity"));	//购买数量
			Product pro  = new ProductServiceImpl().finBtnProduct(productid);
			if(pro.getStock()-stock <= -1) {
				result.returnNo("商品数量不足");
			}else {
				CartUtil cart = getCartFromSession(request);
				result = cart.addlist(pro, stock);
				if (result.getStatus() == Constants.ReturnResult.SUCCESS) {
					cart.setSum((EmptyUtils.isEmpty(cart.getSum()) ? 0.0 : cart.getSum()) + (pro.getPrice() * stock * 1.0));
				}
			}
		}
		return result;
	}
	
	/**
	 * 刷新购物车
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public String refreshCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();
		CartUtil cart = getCartFromSession(request);
        double sum = 0.0;
        for (Cart item : cart.getList()) {
            sum = sum + item.getStock() * item.getProduct().getPrice();
            //item.setPrice(item.getStock() * item.getProduct().getPrice());
        }
        cart.setSum(sum);
		session.setAttribute("cart", cart);// 全部的商品
		return "/common/pre/searchBar";
	}
	

	private CartUtil getCartFromSession(HttpServletRequest request) throws Exception {
		HttpSession session = request.getSession();
		// 获取对象！
		CartUtil cart = (CartUtil) session.getAttribute("cart");
		if (cart == null) {
			cart = new CartUtil();
			session.setAttribute("cart", cart);
		}
		return cart;
	}

	public String RefreshCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//显示三层分类
		List<ProductCategory> list1 = new ProductServiceImpl().finSelectProductCategory(1);
		List<ProductCategory> list2 = new ProductServiceImpl().finSelectProductCategory(2);
		List<ProductCategory> list3 = new ProductServiceImpl().finSelectProductCategory(3);
		//查询分类的结果存入request域中
		request.setAttribute("list", list1);
		request.setAttribute("list2", list2);
		request.setAttribute("list3", list3);
		
		return "/pre/settlement/toSettlement";
	}
	
	/**
	 * 跳转到购物车页面！
	 * @param request
	 * @param response
	 * @return
	 */
	public String settlement1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		CartUtil cart = getCartFromSession(request);
		// 访问三层！
		double sum = 0.0;
        for (Cart item : cart.getList()) {
            sum = sum + item.getStock() * item.getProduct().getPrice();
            //item.setPrice(item.getStock() * item.getProduct().getPrice());
        }
        cart.setSum(sum);
		// 放置对象！
		request.getSession().setAttribute("cart", cart);
		return "/pre/settlement/settlement1";
	}
	
	public String settlement2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		User user = (User)request.getSession().getAttribute("easybuyUserLogin");
		// 访问三层！
		List<UserAddress> userAddressList = new UserServiceImpl().finUserAddress(user.getId());// 获取用户收货地址
		// 放置对象！
		request.setAttribute("userAddressList", userAddressList);
		return "/pre/settlement/settlement2";
	}
	
	/**
	 * 生成订单！
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public Object settlement3(HttpServletRequest request, HttpServletResponse response) throws Exception {
		CartUtil cart = getCartFromSession(request);
		// 计算总价格
		double sum = 0.0;
        for (Cart item : cart.getList()) {
            sum = sum + item.getStock() * item.getProduct().getPrice();
            //item.setPrice(item.getStock() * item.getProduct().getPrice());
        }
        cart.setSum(sum);
		User user = (User)request.getSession().getAttribute("easybuyUserLogin");
		ReturnResult result = checkCart(request);
		if (result.getStatus() == Constants.ReturnResult.FAIL) {
			return result;
		}
		// 新增地址
		String addressId = request.getParameter("addressId");
		String newAddress = request.getParameter("newAddress");
		String newRemark = request.getParameter("newRemark");
		// 创建对象！
		UserAddress userAddress = new UserAddress();
		if (addressId.equals("-1")) {
			HttpSession session = request.getSession();
			User user1 = (User) session.getAttribute("easybuyUserLogin");
			userAddress.setRemark(newRemark);
			userAddress.setAddress(newAddress);
			userAddress.setUserId(user1.getId());
			userAddress.setId(new UserServiceImpl().finUserAddress(userAddress));
		} else {
			userAddress = new UserServiceImpl().finUserAddressID(Integer.parseInt(addressId));
		}
		// 生成订单
		Order order = new OrderServiceImpl().payShoppingCart(cart, user, userAddress.getAddress());
		clearCart(request, response);
		request.setAttribute("currentOrder", order);
		return "/pre/settlement/settlement3";
	}
	

	/**
	 * 判断购物车信息！
	 * @param request
	 * @return
	 * @throws Exception
	 */
	private ReturnResult checkCart(HttpServletRequest request) throws Exception {
		ReturnResult result = new ReturnResult();
		CartUtil cart = getCartFromSession(request);
		// 
		double sum = 0.0;
        for (Cart item : cart.getList()) {
            sum = sum + item.getStock() * item.getProduct().getPrice();
            //item.setPrice(item.getStock() * item.getProduct().getPrice());
        }
        cart.setSum(sum);
		// 循环！
		for (Cart item : cart.getList()) {
			// 访问三层！
			Product product = new ProductServiceImpl().finBtnProduct(item.getProduct().getId());
			if (product.getStock() < item.getStock()) {
				return result.returnNo(product.getName() + "商品数量不足");
			}
		}
		return result.returnYes();
	}
	
	/**
	 * 删除购物车商品
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ReturnResult modCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ReturnResult result = new ReturnResult();
		HttpSession session = request.getSession();
		int proid = Integer.parseInt(request.getParameter("entityId"));
		String quantityStr = request.getParameter("quantity");
		CartUtil cart = (CartUtil) session.getAttribute("cart");
		Integer quantity = 0;
    	if (!EmptyUtils.isEmpty(quantityStr))
            quantity = Integer.parseInt(quantityStr);
		for (Cart item : cart.getList()) {
            if (item.getProduct().getId()==proid) {
                if (quantity == 0 || quantity < 0) {
                    cart.getList().remove(item);
                    break;
                } else {
                    item.setStock(quantity);
                }
            }
        }
        double sum = 0.0;
        for (Cart item : cart.getList()) {
            sum = sum + item.getStock() * item.getProduct().getPrice();
        }
        cart.setSum(sum);
		session.setAttribute("cart", cart);// 全部的商品
		return result.returnYes();
	}
	
	/**
	 * 清空购物车！
	 *
	 * @param request
	 * @param response
	 */
	public ReturnResult clearCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ReturnResult result = new ReturnResult();
		// 结账后清空购物车、
		request.getSession().removeAttribute("cart");
		result.returnYes(null);
		return result;
	}

	@Override
	public Class<?> getServletClass() {
		return CartServlet.class;
	}


}
